package com.org.javabody.ReflectApi;

import java.lang.reflect.Method;

public class ReflectApi {

	public int add(int a, int b) {
		return a+b;
	}
	public String getMessage(String str) {
		return str;
	}

	public void normal() {
		// 1.以前的常规执行手段
		System.out.println(this.add(1, 1));
		System.out.println(this.getMessage("妈的智障!"));
	}
	public void reflect() throws Exception{
		// 2.通过反射的方式
		Class<?> cl = ReflectApi.class; //类名.class
		Object in = cl.newInstance(); // 生成新的对象：用newInstance()方法

		// 通过反射调用方法

		// 首先需要获得与该方法对应的Method对象

		Method addMethod = cl.getMethod("add", new Class[] { int.class,int.class });
		Object result = addMethod.invoke(in, new Object[] { 1, 1 });
		System.out.println(result);

		Method echoMethod = cl.getDeclaredMethod("getMessage", new Class[]{String.class});
		Object result2 = echoMethod.invoke(in, new Object[]{"妈的智障!"});
		System.out.println(result2);
	}
	public static void main(String[] args) throws Exception {
		ReflectApi re = new ReflectApi();
		re.normal();
		re.reflect();
	}
}
